<?php
/**
*
* @package express
* @version $Id: express.php,v 1.020 2008/03/18 07:24:00 nedka Exp $
* @copyright (c) 2008 nedka (Nguyen Dang Khoa)
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();
$user->add_lang('mods/express');

// Grab data
$mode = request_var('mode', '');
$action = request_var('action', '');
$article_id = request_var('article', 0);
$cat_id = request_var('cat', 0);

// Check our mode...
if (!in_array($mode, array('', 'view', 'print', 'email', 'search', 'delete_comment')) || !$cat_id)
{
	trigger_error('NO_MODE');
}

switch ($mode)
{
	case 'email':
	break;

	default:
		// Can this user view articles?
		if (!$auth->acl_gets('u_express'))
		{
			if ($user->data['user_id'] != ANONYMOUS)
			{
				trigger_error('NO_VIEW_ARTICLES');
			}

			login_box('', ((isset($user->lang['LOGIN_EXPLAIN_' . strtoupper($mode)])) ? $user->lang['LOGIN_EXPLAIN_' . strtoupper($mode)] : $user->lang['LOGIN_EXPLAIN_LIST']));
		}
	break;
}

$start = request_var('start', 0);
$submit = (isset($_POST['submit'])) ? true : false;

$default_key = 't';
$sort_key = request_var('sk', $default_key);
$sort_dir = request_var('sd', 'd');

// What do you want to do today? ... oops, I think that line is taken ...
switch ($mode)
{
	case 'view':
	case 'print':
	case 'delete_comment':

		// Display a profile
		if (!$article_id && !$cat_id)
		{
			trigger_error('NO_ARTICLE');
		}

		// Get article...
		$sql = 'SELECT *
			FROM ' . EXPRESS_ARTICLES_TABLE . "
			WHERE article_cat = $cat_id
				AND article_id = $article_id";
		$result = $db->sql_query($sql);
		$article = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		if (!$article)
		{
			trigger_error('NO_ARTICLE');
		}

		$article_id = (int) $article['article_id'];

		// Update views counter
		$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . ' SET article_views = article_views + 1 WHERE article_id = ' . $article_id;
		$db->sql_query($sql);

		// Get similar articles
		if (!empty($article['article_similar']))
		{
			$similar = '';
			$sql = 'SELECT article_id, article_cat, article_title, article_time
				FROM ' . EXPRESS_ARTICLES_TABLE . '
				WHERE article_id IN (' . $article['article_similar'] . ')';
			$result = $db->sql_query($sql);

			while ($row = $db->sql_fetchrow($result))
			{
				$similar .= (($similar != '') ? ', ' : '') . '<a href="' . append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['article_cat'] . '&amp;mode=view&amp;article=' . $row['article_id']) . '">' . $row['article_title'] . '</a> (' . $user->format_date($row['article_time']) . ')';
			}
			$db->sql_freeresult($result);
		}
		else
		{
			$similar = '';
		}

		// Get more articles
		$more_articles = '';
		$sql = 'SELECT article_id, article_cat, article_title, article_time
			FROM ' . EXPRESS_ARTICLES_TABLE . '
			WHERE article_cat = ' . $article['article_cat'] . "
				AND article_id <> $article_id
			ORDER BY article_time DESC";
		$result = $db->sql_query_limit($sql, $config['express_more_articles_limit']);

		while ($row = $db->sql_fetchrow($result))
		{
			$more_articles .= '&raquo; <a href="' . append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $row['article_cat'] . '&amp;mode=view&amp;article=' . $row['article_id']) . '">' . $row['article_title'] . '</a> (' . $user->format_date($row['article_time']) . ')<br />';
		}
		$db->sql_freeresult($result);

		// Rating articles
		$sql = 'SELECT *
			FROM ' . EXPRESS_RATES_TABLE . '
			WHERE user_id = ' . $user->data['user_id'] . "
				AND article_id = $article_id";
		$result = $db->sql_query($sql);
		$rates = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		if (!$rates && $user->data['user_id'] != ANONYMOUS)
		{
			$user_rates = request_var('user_rates', 5);// Default 5/10 :)

			$user_rates_list = array(
				'2'		=> array($user->lang['RATES_2'], 2),// Rate 1 as first
				'3'		=> array($user->lang['RATES_3'], 3),
				'4'		=> array($user->lang['RATES_4'], 4),
				'5'		=> array($user->lang['RATES_5'], 5),
				'6'		=> array($user->lang['RATES_6'], 6),
				'7'		=> array($user->lang['RATES_7'], 7),
				'8'		=> array($user->lang['RATES_8'], 8),
				'9'		=> array($user->lang['RATES_9'], 9),
				'10'	=> array($user->lang['RATES_10'], 10),
			);

			$s_user_rates_options = '<option value="1"' . ((!$user_rates) ? ' selected="selected"' : '') . '>' . $user->lang['RATES_1'] . '</option>';

			foreach ($user_rates_list as $user_rates_var => $user_rates_ary)
			{
				$selected = ($user_rates && $user_rates_ary[1] == $user_rates) ? ' selected="selected"' : '';
				$s_user_rates_options .= '<option value="' . $user_rates_ary[1] . '" ' . $selected . '>' . $user_rates_ary[0] . '</option>';
			}

			if ($submit)
			{
				// Insert rating data
				$sql_ary = array(
					'article_id'	=> $article_id,
					'user_id'		=> $user->data['user_id'],
					'user_ip'		=> $user->ip,
					'rates'			=> $user_rates,
				);

				$sql = 'INSERT INTO ' . EXPRESS_RATES_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
				$db->sql_query($sql);

				// Update rating times of this item
				$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . " SET article_ratings = article_ratings + 1 WHERE article_id = $article_id";
				$db->sql_query($sql);

				// Calculate rating values
				$sql = 'SELECT SUM(rates) as total_rates
					FROM ' . EXPRESS_RATES_TABLE . "
					WHERE article_id = $article_id";
				$result = $db->sql_query($sql);
				$total_rates = (int) $db->sql_fetchfield('total_rates');
				$db->sql_freeresult($result);

				// Update rating data
				$article_rates = round($total_rates / max(1, $article['article_ratings'] + 1), 0);

				$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . " SET article_rates = $article_rates WHERE article_id = $article_id";
				$db->sql_query($sql);

				redirect(append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=view&amp;article=$article_id"));
			}
		}
		else
		{
			$s_user_rates_options = '';
		}

		// Get comments about this article
		$sql = 'SELECT *
			FROM ' . EXPRESS_COMMENTS_TABLE . "
			WHERE article_id = $article_id
			ORDER BY comment_time";
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$template->assign_block_vars('comments', array(
				'COMMENT'	=> generate_text_for_display($row['comment'], $row['comment_uid'], $row['comment_bitfield'], $row['comment_options']),
				'POSTER'	=> get_username_string('full', $row['poster_id'], $row['poster_username'], $row['poster_colour']),
				'TIME'		=> $user->format_date($row['comment_time']),

				'U_DELETE'	=> ($auth->acl_get('a_express')) ? append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=delete_comment&amp;article=$article_id&amp;comment_id=" . $row['comment_id']) : '',
			));	
		}
		$db->sql_freeresult($result);

		// Comment articles
		if ($user->data['user_id'] != ANONYMOUS)
		{
			include_once($phpbb_root_path . 'includes/functions_display.' . $phpEx);

			$user->add_lang('posting');

			// Assigning custom bbcodes
			display_custom_bbcodes();

			$comment = utf8_normalize_nfc(request_var('comment', '', true));

			if ($submit)
			{
				// Insert comment data
				$sql_ary = array(
					'article_id'		=> $article_id,
					'poster_id'			=> $user->data['user_id'],
					'poster_username'	=> $user->data['username'],
					'poster_colour'		=> $user->data['user_colour'],
					'poster_ip'			=> $user->ip,
					'comment'			=> $comment,
					'comment_uid'		=> '',
					'comment_options'	=> 7,
					'comment_bitfield'	=> '',
					'comment_time'		=> time(),
				);

				// Get data for block text if specified
				if ($sql_ary['comment'])
				{
					generate_text_for_storage($sql_ary['comment'], $sql_ary['comment_uid'], $sql_ary['comment_bitfield'], $sql_ary['comment_options'], request_var('comment_parse_bbcode', false), request_var('comment_parse_urls', false), request_var('comment_parse_smilies', false));
				}

				$sql = 'INSERT INTO ' . EXPRESS_COMMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
				$db->sql_query($sql);

				$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . " SET article_comments = article_comments + 1 WHERE article_id = $article_id";
				$db->sql_query($sql);

				redirect(append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=view&amp;article=$article_id"));
			}

			// Comment with BBCode support
			$comment_data = array(
				'text'			=> (isset($article['comment'])) ? $article['comment'] : '',
				'allow_bbcode'	=> true,
				'allow_smilies'	=> true,
				'allow_urls'	=> true
			);

			// Parse block_text if specified
			if (isset($article['comment']))
			{
				if (!isset($article['comment_uid']))
				{
					// Before we are able to display the preview and plane text, we need to parse our request_var()'d value...
					$article['comment_uid'] = '';
					$article['comment_bitfield'] = '';
					$article['comment_options'] = 0;

					generate_text_for_storage($article['comment'], $article['comment_uid'], $article['comment_bitfield'], $article['comment_options'], request_var('comment_allow_bbcode', false), request_var('comment_allow_urls', false), request_var('comment_allow_smilies', false));
				}

				// Decode...
				$comment_data = generate_text_for_edit($article['comment'], $article['comment_uid'], $article['comment_options']);
			}
		}

		// Delete comments
		if ($mode == 'delete_comment' && $auth->acl_get('a_express'))
		{
			$comment_id = request_var('comment_id', 0);

			$sql = 'DELETE FROM ' . EXPRESS_COMMENTS_TABLE . " WHERE comment_id = $comment_id";
			$db->sql_query($sql);

			$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . " SET article_comments = article_comments - 1 WHERE article_id = $article_id";
			$db->sql_query($sql);

			redirect(append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=view&amp;article=$article_id"));
		}

		// Output URL for printable page
		$print_url = $config['server_protocol'] . $config['server_name'] . $config['script_path'] . "/express.$phpEx?cat=" . $cat_id . "&amp;mode=view&amp;article=$article_id";

		$template->assign_vars(show_article($article));

		$template->assign_vars(array(
			'RATE_DETAILS'		=> sprintf($user->lang['RATE_DETAILS'], $article['article_rates'], 10, $article['article_ratings']),
			'SIMILAR'			=> $similar,
			'MORE_ARTICLES'		=> $more_articles,
			'PRINT_URL'			=> $print_url,
			'EXPRESS_COPYRIGHT'	=> sprintf($user->lang['EXPRESS_COPYRIGHT'], $config['express_copyright']),
			'COMMENT'			=> ($user->data['user_id'] != ANONYMOUS) ? $comment_data['text'] : '',

			'EDIT_IMG'				=> $user->img('icon_post_edit', 'EDIT_ARTICLE'),
			'DELETE_IMG'			=> $user->img('icon_post_delete', 'DELETE_ARTICLE'),
			'DELETE_COMMENT_IMG'	=> $user->img('icon_post_delete', 'DELETE_COMMENT'),

			'U_EDIT'	=> ($auth->acl_get('a_express')) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", "i=express_articles&amp;mode=articles&amp;action=edit&amp;id=$article_id", true, $user->session_id) : '',
			'U_DELETE'	=> ($auth->acl_get('a_express')) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", "i=express_articles&amp;mode=articles&amp;action=delete&amp;id=$article_id", true, $user->session_id) : '',

			'S_USER_RATES_OPTIONS'		=> $s_user_rates_options,
			'S_MODE_ACTION'				=> append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=view&amp;article=$article_id"),
			'S_COMMENT_BBCODE_CHECKED'	=> ($user->data['user_id'] != ANONYMOUS && $comment_data['allow_bbcode']) ? true : false,
			'S_COMMENT_SMILIES_CHECKED'	=> ($user->data['user_id'] != ANONYMOUS && $comment_data['allow_smilies']) ? true : false,
			'S_COMMENT_URLS_CHECKED'	=> ($user->data['user_id'] != ANONYMOUS && $comment_data['allow_urls']) ? true : false,
		));

		// Now generate page title
		$page_title = ($mode == 'print') ? $article['article_title'] : sprintf($user->lang['VIEWING_ARTICLE'], $article['article_title']);
		$template_html = ($mode == 'print') ? 'express_print.html' : 'express_view.html';

	break;

	case 'email':

		// Send an email
		$page_title = $user->lang['SEND_EMAIL'];
		$template_html = 'express_email.html';

		add_form_key('express_email');

		if (!$config['email_enable'])
		{
			trigger_error('EMAIL_DISABLED');
		}

		if (!$auth->acl_get('u_sendemail'))
		{
			trigger_error('NO_EMAIL');
		}

		// Are we trying to abuse the facility?
		if (time() - $user->data['user_emailtime'] < $config['flood_interval'])
		{
			trigger_error('FLOOD_EMAIL_LIMIT');
		}

		// Determine action...
		$article_id = request_var('article', 0);

		// Send email article...
		if ($article_id)
		{
			// Send article heads-up to email address
			$sql = 'SELECT article_id, article_cat, article_title, article_intro
				FROM ' . EXPRESS_ARTICLES_TABLE . "
				WHERE article_id = $article_id";
			$result = $db->sql_query($sql);
			$row = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			if (!$row)
			{
				trigger_error('NO_ARTICLE');
			}
		}
		else
		{
			trigger_error('NO_EMAIL');
		}

		$error = array();

		$name = utf8_normalize_nfc(request_var('name', '', true));
		$email = request_var('email', '');
		$email_lang = request_var('lang', $config['default_lang']);
		$subject = utf8_normalize_nfc(request_var('subject', '', true));
		$message = utf8_normalize_nfc(request_var('message', '', true));
		$cc = (isset($_POST['cc_email'])) ? true : false;

		if ($submit)
		{
			if (!check_form_key('express_email'))
			{
				$error[] = 'FORM_INVALID';
			}

			if (!$email || !preg_match('/^' . get_preg_expression('email') . '$/i', $email))
			{
				$error[] = $user->lang['EMPTY_ADDRESS_EMAIL'];
			}

			if (!$name)
			{
				$error[] = $user->lang['EMPTY_NAME_EMAIL'];
			}

			if (!sizeof($error))
			{
				$sql = 'UPDATE ' . USERS_TABLE . '
					SET user_emailtime = ' . time() . '
					WHERE user_id = ' . $user->data['user_id'];
				$result = $db->sql_query($sql);

				include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
				$messenger = new messenger(false);
				$email_tpl = 'express_email';

				$mail_to_users = array();

				$mail_to_users[] = array(
					'email_lang'		=> $email_lang,
					'email'				=> $email,
					'name'				=> $name,
					'username'			=> '',
					'to_name'			=> $name,
					'user_jabber'		=> '',
					'user_notify_type'	=> NOTIFY_EMAIL,
					'article_id'		=> $row['article_id'],
					'article_title'		=> $row['article_title'],
					'article_intro'		=> $row['article_intro'],
				);

				// Ok, now the same email if CC specified, but without exposing the users email address
				if ($cc)
				{
					$mail_to_users[] = array(
						'email_lang'		=> $user->data['user_lang'],
						'email'				=> $user->data['user_email'],
						'name'				=> $user->data['username'],
						'username'			=> $user->data['username'],
						'to_name'			=> $name,
						'user_jabber'		=> $user->data['user_jabber'],
						'user_notify_type'	=> NOTIFY_EMAIL,
						'article_id'		=> $row['article_id'],
						'article_title'		=> $row['article_title'],
						'article_intro'		=> $row['article_intro'],
					);
				}

				foreach ($mail_to_users as $row)
				{
					$messenger->template($email_tpl, $row['email_lang']);
					$messenger->replyto($user->data['user_email']);
					$messenger->to($row['email'], $row['name']);

					$notify_type = NOTIFY_EMAIL;

					$messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
					$messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
					$messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
					$messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);

					$messenger->assign_vars(array(
						'BOARD_CONTACT'	=> $config['board_contact'],
						'TO_USERNAME'	=> htmlspecialchars_decode($row['to_name']),
						'FROM_USERNAME'	=> htmlspecialchars_decode($user->data['username']),
						'MESSAGE'		=> htmlspecialchars_decode($message),
						'ARTICLE_TITLE'	=> htmlspecialchars_decode($row['article_title']),
						'ARTICLE_INTRO'	=> htmlspecialchars_decode($row['article_intro']),
						'U_ARTICLE'		=> generate_board_url() . "/express.$phpEx?cat=" . $row['article_cat'] . "&mode=view&article=$article_id",
					));

					$messenger->send($notify_type);
				}

				meta_refresh(3, append_sid("{$phpbb_root_path}index.$phpEx"));
				$message = sprintf($user->lang['RETURN_ARTICLE'],  '<a href="' . append_sid("{$phpbb_root_path}express.$phpEx", "cat={$row['article_cat']}&amp;article=$article_id") . '">', '</a>');
				trigger_error($user->lang['EMAIL_SENT'] . '<br /><br />' . $message);
			}
		}

		$template->assign_vars(array(
			'ERROR_MESSAGE'	=> (sizeof($error)) ? implode('<br />', $error) : '',

			'ARTICLE_TITLE'	=> $row['article_title'],
			'EMAIL'			=> $email,
			'NAME'			=> $name,

			'S_LANG_OPTIONS'	=> language_select($email_lang),
			'S_POST_ACTION'		=> append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=email&amp;article=" . $article_id))
		);

	break;

	default:
		// The basic article list
		$page_title = $user->lang['ARTICLE_LIST'];
		$template_html = 'express_body.html';

		// Sorting
		$sort_key_text = array('t' => $user->lang['SORT_ARTICLE_TIME'], 'v' => $user->lang['SORT_ARTICLE_VIEWS'], 'c' => $user->lang['SORT_ARTICLE_COMMENTS']);
		$sort_key_sql = array('t' => 'article_time', 'v' => 'article_views', 'c' => 'article_comments');
		$sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);

		$s_sort_key = '';
		foreach ($sort_key_text as $key => $value)
		{
			$selected = ($sort_key == $key) ? ' selected="selected"' : '';
			$s_sort_key .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
		}

		$s_sort_dir = '';
		foreach ($sort_dir_text as $key => $value)
		{
			$selected = ($sort_dir == $key) ? ' selected="selected"' : '';
			$s_sort_dir .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
		}

		// Additional sorting options for user search ... if search is enabled, if not
		// then only admins can make use of this (for ACP functionality)
		$sql_where = $order_by = '';

		$form = request_var('form', '');
		$field = request_var('field', '');

		// We validate form and field here, only id/class allowed
		$form = (!preg_match('/^[a-z0-9_-]+$/i', $form)) ? '' : $form;
		$field = (!preg_match('/^[a-z0-9_-]+$/i', $field)) ? '' : $field;

		if ($mode == 'search' && $config['load_search'])
		{
			$time_select = request_var('time_select', 'lt');
			$time = explode('-', request_var('time', ''));

			$find_key_match = array('lt' => '<', 'gt' => '>', 'eq' => '=');
			$find_time = array('lt' => $user->lang['BEFORE'], 'gt' => $user->lang['AFTER']);

			$s_find_time = '';
			foreach ($find_time as $key => $value)
			{
				$selected = ($time_select == $key) ? ' selected="selected"' : '';
				$s_find_time .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
			}

			$sql_where .= (sizeof($time) > 1) ? " AND article_time " . $find_key_match[$time_select] . ' ' . gmmktime(0, 0, 0, intval($time[1]), intval($time[2]), intval($time[0])) : '';
		}

		// Sorting and order
		if (!isset($sort_key_sql[$sort_key]))
		{
			$sort_key = $default_key;
		}

		$order_by .= $sort_key_sql[$sort_key] . ' ' . (($sort_dir == 'a') ? 'ASC' : 'DESC');

		// Count the articles...
		$sql = 'SELECT COUNT(article_id) AS total_articles
			FROM ' . EXPRESS_ARTICLES_TABLE . "
			WHERE article_cat = $cat_id
			$sql_where";
		$result = $db->sql_query($sql);
		$total_articles = (int) $db->sql_fetchfield('total_articles');
		$db->sql_freeresult($result);

		// Build a relevant pagination_url
		$params = $sort_params = array();

		// We do not use request_var() here directly to save some calls (not all variables are set)
		$check_params = array(
			'g'				=> array('g', 0),
			'sk'			=> array('sk', $default_key),
			'sd'			=> array('sd', 'a'),
			'form'			=> array('form', ''),
			'field'			=> array('field', ''),
			'time_select'	=> array('time_select', 'lt'),
			'time'			=> array('time', ''),
		);

		foreach ($check_params as $key => $call)
		{
			if (!isset($_REQUEST[$key]))
			{
				continue;
			}

			$param = call_user_func_array('request_var', $call);
			$param = urlencode($key) . '=' . ((is_string($param)) ? urlencode($param) : $param);
			$params[] = $param;

			if ($key != 'sk' && $key != 'sd')
			{
				$sort_params[] = $param;
			}
		}

		$u_hide_find_article = append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id", implode('&amp;', $params));

		$params[] = "cat=$cat_id&amp;mode=$mode";
		$sort_params[] = "cat=$cat_id&amp;mode=$mode";
		$pagination_url = append_sid("{$phpbb_root_path}express.$phpEx", implode('&amp;', $params));
		$sort_url = append_sid("{$phpbb_root_path}express.$phpEx", implode('&amp;', $sort_params));

		unset($params, $sort_params);

		// Some search user specific data
		if ($mode == 'search' && ($config['load_search'] || $auth->acl_get('a_')))
		{
			$template->assign_vars(array(
				'TIME'	=> implode('-', $time),

				'S_SEARCH'			=> true,
				'S_FORM_NAME'		=> $form,
				'S_FIELD_NAME'		=> $field,
				'S_SORT_OPTIONS'	=> $s_sort_key,
				'S_TIME_OPTIONS'	=> $s_find_time,
				'S_SEARCH_ACTION'	=> append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=search&amp;form=$form&amp;field=$field"),
			));
		}

		// Get us some articles
		$sql = "SELECT article_id
			FROM " . EXPRESS_ARTICLES_TABLE . "
			WHERE article_cat = $cat_id
				$sql_where
			ORDER BY $order_by";
		$result = $db->sql_query_limit($sql, $config['express_articles_per_page'], $start);

		$article_list = array();
		while ($row = $db->sql_fetchrow($result))
		{
			$article_list[] = (int) $row['article_id'];
		}
		$db->sql_freeresult($result);

		// So, did we get any articles?
		if (sizeof($article_list))
		{
			// Do the SQL thang
			$sql = 'SELECT *
				FROM ' . EXPRESS_ARTICLES_TABLE . '
				WHERE ' . $db->sql_in_set('article_id', $article_list);
			$result = $db->sql_query($sql);

			$id_cache = array();
			while ($row = $db->sql_fetchrow($result))
			{
				$id_cache[$row['article_id']] = $row;
			}
			$db->sql_freeresult($result);

			for ($i = 0, $end = sizeof($article_list); $i < $end; ++$i)
			{
				$article_id = $article_list[$i];
				$row =& $id_cache[$article_id];

				$articlerow = array_merge(show_article($row), array(
					'ROW_NUMBER'		=> $i + ($start + 1),
					'U_VIEW_ARTICLE'	=> append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=view&amp;article=" . $article_id),
				));

				$template->assign_block_vars('articlerow', $articlerow);

				unset($id_cache[$article_id]);
			}
		}

		// Get the category name
		$sql = 'SELECT cat_name
			FROM ' . EXPRESS_CATEGORIES_TABLE . "
			WHERE cat_id = $cat_id";
		$result = $db->sql_query($sql);
		$cat_name = (string) $db->sql_fetchfield('cat_name');
		$db->sql_freeresult($result);

		// Generate page
		$template->assign_vars(array(
			'PAGINATION'		=> generate_pagination($pagination_url, $total_articles, $config['express_articles_per_page'], $start),
			'PAGE_NUMBER'		=> on_page($total_articles, $config['express_articles_per_page'], $start),
			'TOTAL_ARTICLES'	=> ($total_articles == 1) ? $user->lang['LIST_ARTICLE'] : sprintf($user->lang['LIST_ARTICLES'], $total_articles),

			'CAT_NAME'			=> $cat_name,
			'EXPRESS_COPYRIGHT'	=> sprintf($user->lang['EXPRESS_COPYRIGHT'], $config['express_copyright']),

			'U_FIND_ARTICLE'		=> ($config['load_search']) ? append_sid("{$phpbb_root_path}express.$phpEx", "cat=$cat_id&amp;mode=search") : '',
			'U_HIDE_FIND_ARTICLE'	=> ($mode == 'search') ? $u_hide_find_article : '',
			'U_SORT_TIME'			=> $sort_url . '&amp;sk=t&amp;sd=' . (($sort_key == 't' && $sort_dir == 'a') ? 'd' : 'a'),
			'U_SORT_VIEWS'			=> $sort_url . '&amp;sk=v&amp;sd=' . (($sort_key == 'v' && $sort_dir == 'a') ? 'd' : 'a'),
			'U_SORT_COMMENTS'		=> $sort_url . '&amp;sk=c&amp;sd=' . (($sort_key == 'c' && $sort_dir == 'a') ? 'd' : 'a'),

			'S_MODE_SELECT'		=> $s_sort_key,
			'S_ORDER_SELECT'	=> $s_sort_dir,
			'S_MODE_ACTION'		=> $pagination_url,
		));

	break;
}

// Output the page
page_header($page_title);

$template->set_filenames(array(
	'body' => $template_html)
);

page_footer();

/**
* Prepare profile data
*/
function show_article($data)
{
	global $config, $template, $user, $phpEx, $phpbb_root_path;

	// Dump it out to the template
	return array(
		'TITLE'			=> ($data['article_title']) ? $data['article_title'] : '',
		'INTRO'			=> ($data['article_intro']) ? str_replace("\n", '<br />', $data['article_intro']) : '',
		'IMAGE'			=> $phpbb_root_path . $config['express_article_images_path'] . '/' . $data['article_image'],
		'TIME'			=> $user->format_date($data['article_time']),
		'VIEWS'			=> $data['article_views'],
		'RATES'			=> ($data['article_rates']) ? $data['article_rates'] : 0,
		'RATINGS'		=> ($data['article_ratings']) ? $data['article_ratings'] : 0,
		'RATE_IMAGE'	=> '<img src="' . $phpbb_root_path . 'images/rates/rate_' . $data['article_rates'] . '.png" alt="' . $data['article_rates'] . '/10" title="' . $data['article_rates'] . '/10" />',
		'COMMENTS'		=> $data['article_comments'],
		'SOURCE'		=> $data['article_source'],
		'CONTENT'		=> generate_text_for_display($data['article_content'], $data['article_content_uid'], $data['article_content_bitfield'], $data['article_content_options']),
		'URL'			=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $data['article_cat'] . '&amp;mode=view&amp;article=' . $data['article_id']),

		'U_VIEW_CAT'	=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $data['article_cat']),
		'U_PRINT'		=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $data['article_cat'] . '&amp;mode=print&amp;article=' . $data['article_id']),
		'U_EMAIL'		=> append_sid("{$phpbb_root_path}express.$phpEx", 'cat=' . $data['article_cat'] . '&amp;mode=email&amp;article=' . $data['article_id']),

		'L_VIEWING_ARTICLE'	=> sprintf($user->lang['VIEWING_ARTICLE'], $data['article_title']),

		'S_IMAGE'	=> ($data['article_image']) ? true : false,
	);
}

?>